//
//  ExamViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/4/19.
//

#import "ExamViewController.h"
#import "ExamCateListView.h"
#import "BasicClassViewController.h"
#import "ExaminationPaperViewController.h"
#import "ExamCateManager.h"
#import "ExamCateModel.h"
#import "ExamTestPaperListManager.h"
#import "ExamPaperYearModel.h"
#import "ExamPaperYearListModel.h"
#import "LoginViewController.h"
#import "ExamPaperUnlockManager.h"
#import "ExamCollectionViewController.h"

@interface ExamViewController ()<JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)NSMutableArray *cateArr;
@property(nonatomic,assign)NSInteger cate_index;
@property(nonatomic,strong)UIScrollView *bgScrollView;
@property(nonatomic,strong)ExamCateManager *cateManager;
@property(nonatomic,strong)UIButton *collectBtn;
@property(nonatomic,strong)UIScrollView *cateScrollView;
@property(nonatomic,strong)ExamTestPaperListManager *paperListManager;
@property(nonatomic,strong)ExamPaperUnlockManager *unlockManager;
@property(nonatomic,strong)ExamPaperYearListModel *selModel;
@property(nonatomic,copy)NSString *grammar;
@property(nonatomic,strong)UIView *navView;

@end

@implementation ExamViewController

-(ExamCateManager *)cateManager{
    if(!_cateManager){
        _cateManager = [[ExamCateManager alloc]init];
        _cateManager.delegate = self;
    }
    return _cateManager;
}

-(NSMutableArray *)cateArr{
    if(!_cateArr){
        _cateArr = [NSMutableArray array];
    }
    return _cateArr;
}

-(ExamTestPaperListManager *)paperListManager{
    if(!_paperListManager){
        _paperListManager = [[ExamTestPaperListManager alloc]init];
        _paperListManager.delegate = self;
    }
    return _paperListManager;
}

-(ExamPaperUnlockManager *)unlockManager{
    if(!_unlockManager){
        _unlockManager = [[ExamPaperUnlockManager alloc]init];
        _unlockManager.delegate = self;
    }
    return _unlockManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    [self createUI];
    [self getCateData];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSuccess:) name:@"loginSuccess" object:nil];
        
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logoutSuccess) name:@"logoutSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(examScoreRefresh:) name:@"examScoreRefresh" object:nil];
    
}

#pragma mark - 试卷成绩刷新
-(void)examScoreRefresh:(NSNotification*)notifi{
    if(notifi.object){
        NSArray *arr = notifi.object;
        if(arr.count == 2){
            NSString *score = arr[0];
            NSString *paperId = arr[1];
            ExamCateListView *listView = [self.bgScrollView viewWithTag:1000+self.cate_index];
            NSMutableArray *dataArr = [NSMutableArray arrayWithArray:listView.dataArr];
            for(NSInteger i = 0;i < dataArr.count;i++){
                ExamPaperYearModel *yearModel = dataArr[i];
                NSMutableArray *larr = [NSMutableArray arrayWithArray:yearModel.list];
                BOOL isHave = NO;
                for(NSInteger j = 0;j < larr.count;j++){
                    ExamPaperYearListModel *model = larr[j];
                    if([model.paperId isEqualToString:paperId]){
                        model.testScore = score;
                        model.isFinish = @"1";
                        [larr replaceObjectAtIndex:j withObject:model];
                        isHave = YES;
                        break;
                    }
                }
                if(isHave == YES){
                    yearModel.list = larr;
                    [dataArr replaceObjectAtIndex:i withObject:yearModel];
                    break;
                }
            }
            listView.dataArr = dataArr;
            [listView refresh];
        }
    }
}

#pragma mark - 登录成功
-(void)loginSuccess:(NSNotification*)notifi{
    if(self.cateArr.count == 0){
        [self getCateData];
    }else{
        [self loadPaperData];
    }
}

#pragma mark - 退出登录成功
-(void)logoutSuccess{
    if(self.cateArr.count == 0){
        [self getCateData];
    }else{
        [self loadPaperData];
    }
}

#pragma mark - 获取头部分类数据
-(void)getCateData{
    [self.cateManager loadData];
}

#pragma mark - 获取试卷列表数据
-(void)loadPaperData{
    if(self.cate_index < self.cateArr.count){
        ExamCateModel *model = self.cateArr[self.cate_index];
        self.paperListManager.grade = model.dictDataId;
        [self.paperListManager loadData];
    }
}


-(void)createUI{
    
    self.customNavigationBar.hidden = YES;
    
    UIView *navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth, kYM_NAVIGATIONBAR_HEIGHT)];
    navView.backgroundColor = kTopBgColor(self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
    [self.view addSubview:navView];
    self.navView = navView;
    
    self.bgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+6,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-6)];
    self.bgScrollView.backgroundColor = KbgColor;
    self.bgScrollView.scrollEnabled = NO;
    self.bgScrollView.pagingEnabled = YES;
    [self.view addSubview:self.bgScrollView];
    
    CGFloat w68 = [DeviceUtils getAdaptedWidthForDesignWidth:68 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(w68 > 120){
        w68 = 120;
    }
    UIButton *collectBtn = [[UIButton alloc]init];
    collectBtn.backgroundColor = [UIColor clearColor];
    [collectBtn setBackgroundImage:[UIImage imageNamed:@"exam_home_test_logo"] forState:UIControlStateNormal];
    [collectBtn addTarget:self action:@selector(collectBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:collectBtn];
    [collectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(@-30);
        make.right.mas_equalTo(@-6);
        make.width.height.mas_equalTo(w68);
    }];
    self.collectBtn = collectBtn;
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            self.navView.frame = CGRectMake(0, 0, self.currentAvailableWidth, kYM_NAVIGATIONBAR_HEIGHT);
            self.navView.backgroundColor = kTopBgColor(self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            self.bgScrollView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+6,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-6);
            CGFloat w68 = [DeviceUtils getAdaptedWidthForDesignWidth:68 andCurrentAvailableWidth:self.currentAvailableWidth];
            if(w68 > 120){
                w68 = 120;
            }
            [self.collectBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.height.mas_equalTo(w68);
            }];
            self.bgScrollView.contentSize = CGSizeMake(self.cateArr.count*self.currentAvailableWidth,0);
            CGFloat left = 16;
            CGFloat w60 = [DeviceUtils getAdaptedWidthForDesignWidth:60 andCurrentAvailableWidth:self.currentAvailableWidth];
            CGFloat mid = (self.currentAvailableWidth-w60*5-32)/4.0;
            if(self.cateArr.count > 5){
                self.cateScrollView.frame = CGRectMake(0,kYM_STATUSBAR_HEIGHT+16,self.currentAvailableWidth,34);
            }
            for(NSInteger i = 0;i < self.cateArr.count;i++){
                UIButton *cateBtn;
                if(self.cateArr.count > 5){
                    cateBtn = [self.cateScrollView viewWithTag:100+i];
                    [cateBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.width.mas_equalTo(w60);
                        make.top.mas_equalTo(0);
                        make.left.mas_equalTo(left);
                    }];
                }else{
                    cateBtn = [self.view viewWithTag:100+i];
                    [cateBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.width.mas_equalTo(w60);
                        make.top.mas_equalTo(kYM_STATUSBAR_HEIGHT+16);
                        make.left.mas_equalTo(left);
                    }];
                }
                left = left+w60+mid;
                ExamCateListView *listView = [self.view viewWithTag:1000+i];
                listView.frame = CGRectMake(i*self.currentAvailableWidth,0,self.currentAvailableWidth,self.bgScrollView.height);
                listView.currentAvailableWidth = self.currentAvailableWidth;
                [listView refreshWidth];
            }
            
            if(self.cateArr.count > 5){
                self.cateScrollView.contentSize = CGSizeMake(left,0);
            }
            [self.view bringSubviewToFront:self.collectBtn];
            [self.bgScrollView setContentOffset:CGPointMake(self.cate_index*self.currentAvailableWidth,0) animated:NO];
        });
    }
}

#pragma mark - 创建分类按钮
-(void)createCateBtn{
    
    self.bgScrollView.contentSize = CGSizeMake(self.cateArr.count*self.currentAvailableWidth,0);
    __weak typeof(self)self_weak_ = self;
    CGFloat left = 16;
    CGFloat w60 = [DeviceUtils getAdaptedWidthForDesignWidth:60 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat mid = (self.currentAvailableWidth-w60*5-32)/4.0;
    if(self.cateArr.count > 5){
        self.cateScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,kYM_STATUSBAR_HEIGHT+16,self.currentAvailableWidth,34)];
        self.cateScrollView.backgroundColor = [UIColor clearColor];
        self.cateScrollView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:self.cateScrollView];
    }
    for(NSInteger i = 0;i < self.cateArr.count;i++){
        ExamCateModel *model = self.cateArr[i];
        UIButton *cateBtn = [[UIButton alloc]init];
        [cateBtn setTitle:model.dictDataName forState:UIControlStateNormal];
        [cateBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
        [cateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        cateBtn.titleLabel.font = JPUIFontPingFangSCMedium(16);
        cateBtn.layer.cornerRadius = 6;
        cateBtn.layer.masksToBounds = YES;
        cateBtn.tag = 100+i;
        [cateBtn addTarget:self action:@selector(cateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        if(i == self.cate_index){
            cateBtn.selected = YES;
            cateBtn.backgroundColor = KThemeColor;
        }else{
            cateBtn.selected = NO;
            cateBtn.backgroundColor = [UIColor whiteColor];
        }
        if(self.cateArr.count > 5){
            [self.cateScrollView addSubview:cateBtn];
            [cateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(w60);
                make.height.mas_equalTo(@34);
                make.top.mas_equalTo(0);
                make.left.mas_equalTo(left);
            }];
        }else{
            [self.view addSubview:cateBtn];
            [cateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(w60);
                make.height.mas_equalTo(@34);
                make.top.mas_equalTo(kYM_STATUSBAR_HEIGHT+16);
                make.left.mas_equalTo(left);
            }];
        }
        left = left+w60+mid;
        
        ExamCateListView *listView = [[ExamCateListView alloc]initWithFrame:CGRectMake(i*self.currentAvailableWidth,0,self.currentAvailableWidth,self.bgScrollView.height) andIndex:i];
        listView.tag = 1000+i;
        listView.currentAvailableWidth = self.currentAvailableWidth;
        [self.bgScrollView addSubview:listView];
        [listView setTopClickBlock:^{
            NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
            if(userId){
                ExamCateModel *model = self_weak_.cateArr[self_weak_.cate_index];
                BasicClassViewController *vc = [[BasicClassViewController alloc]init];
                vc.grade = model.dictDataId;
                vc.titleStr = self_weak_.grammar;
                [self_weak_.navigationController pushViewController:vc animated:YES];
            }else{
                [self_weak_ login];
            }
        }];
        [listView setListBlock:^(ExamPaperYearListModel * _Nonnull model) {
            self_weak_.selModel = model;
            NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
            if(userId){
//                NSString *loginMode = [[NSUserDefaults standardUserDefaults]objectForKey:@"loginMode"];
//                if(loginMode&&[loginMode isEqualToString:@"4"]){
//                    //游客需要登录
//                    [self_weak_ login];
//                }else{
                    if(model.isLock&&[model.isLock isEqualToString:@"1"]){
                        ExaminationPaperViewController *vc = [[ExaminationPaperViewController alloc]init];
                        vc.listModel = model;
                        [self_weak_.navigationController pushViewController:vc animated:YES];
                    }else{
                        self_weak_.unlockManager.paperId = model.paperId;
                        [self_weak_.unlockManager loadData];
                    }
//                }
            }else{
                [self_weak_ login];
            }
        }];
        listView.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self_weak_ loadPaperData];
        }];
    }
    
    if(self.cateArr.count > 5){
        self.cateScrollView.contentSize =CGSizeMake(left,0);
    }
    
    [self.view bringSubviewToFront:self.collectBtn];
    
}

#pragma mark - 登录
-(void)login{
    LoginViewController *vc = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 分类点击
-(void)cateBtnClick:(UIButton*)btn{
    
    NSInteger index = btn.tag-100;
    UIButton *oldBtn = [self.view viewWithTag:100+self.cate_index];
    oldBtn.selected = NO;
    oldBtn.backgroundColor = [UIColor whiteColor];
    
    btn.selected = YES;
    btn.backgroundColor = KThemeColor;
    self.cate_index = index;
    
    [self loadPaperData];
    
    [self.bgScrollView setContentOffset:CGPointMake(index*self.currentAvailableWidth,0) animated:NO];
    
}

#pragma mark - 收藏夹
-(void)collectBtnClick{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        if(self.cate_index < self.cateArr.count){
            ExamCateModel *model = self.cateArr[self.cate_index];
            ExamCollectionViewController *vc = [[ExamCollectionViewController alloc]init];
            vc.cateModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else{
        [self login];
    }
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.cateManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [ExamCateModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.cateArr = [NSMutableArray arrayWithArray:arr];
        self.cate_index = 0;
        [self createCateBtn];
        [self loadPaperData];
    }
    
    if([manager isEqual:self.paperListManager]){
        NSDictionary *dic = manager.response.content;
        NSString *grammar = [NSString stringWithFormat:@"%@",dic[@"data"][@"grammar"]];
        self.grammar = grammar;
        NSArray *arr = [ExamPaperYearModel mj_objectArrayWithKeyValuesArray:dic[@"data"][@"data"]];
        NSMutableArray *resultArr = [NSMutableArray array];
        for(NSInteger i = 0; i < arr.count;i ++){
            ExamPaperYearModel *model = arr[i];
            NSArray *list = [ExamPaperYearListModel mj_objectArrayWithKeyValuesArray:model.list];
            model.list = list;
            [resultArr addObject:model];
        }
        ExamCateListView *listView = [self.bgScrollView viewWithTag:1000+self.cate_index];
        [listView.tableView.mj_header endRefreshing];
        listView.dataArr = resultArr;
        listView.grammar = grammar?grammar:@"";
        [listView refresh];
    }
    
    if([manager isEqual:self.unlockManager]){
        [self loadPaperData];
        ExaminationPaperViewController *vc = [[ExaminationPaperViewController alloc]init];
        vc.listModel = self.selModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.paperListManager]){
        ExamCateListView *listView = [self.bgScrollView viewWithTag:1000+self.cate_index];
        [listView.tableView.mj_header endRefreshing];
    }
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


@end
